<?php
namespace cms\modules\v1\models\userFund;

use cms\modules\v1\models\Common;
use cms\modules\v1\models\user\User;
use common\models\Functions;
use common\models\Status;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class UserMoneyLog extends \common\models\userFund\UserMoneyLog
{

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @param array $search
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {

            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'change_time DESC, id DESC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);

            $data['data'] = $this->handelList($query);

            $summary = static::getOneByAndWhere($searchWhere['where'], $searchWhere['andWhere'], [
                "SUM(num) as num",
            ]);

            $totalMoney = User::getSumByWhere([], "money");
//
//            $data['summary'] = [
//                "diff_income" => ["key" => "diff_income", "value" => $summary['diff_income']],
//                "self_diff_income" => ["key" => "self_diff_income", "value" => $summary['self_diff_income']],
//                "self_income" => ["key" => "self_income", "value" => $summary['self_income']],
//                "self_volume" => ["key" => "self_volume", "value" => $summary['self_volume']],
//                "team_volume" => ["key" => "team_volume", "value" => $summary['team_volume']],
//            ];

            $data['summary'] = [
                ["key" => "id", "value" => ''],
                ["key" => "user", "value" => ''],
                ["key" => "change_type", "value" => ''],
                ["key" => "num", "value" => (float) $summary['num']],
                ["key" => "before_change", "value" => ''],
                ["key" => "after_change", "value" => "当前总余额：" . $totalMoney],
                ["key" => "change_time", "value" => ''],
                ["key" => "mark", "value" => ''],
            ];

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @return string
     */
    public function getSearch () {
        $where = [];
        $andWhere = [];
        $get = Yii::$app->request->get();
//        $type = Yii::$app->request->get('type',0);
        $loginName = Yii::$app->request->get('login_name',"");
        $startTime = Yii::$app->request->get('start',"");
        $endTime = Yii::$app->request->get('end',"");
        $userId = Yii::$app->request->get('user_id',"");

        if(!empty($userId)) {
            $where['user_id'] = (int)$userId;
        }
        if (!empty($get['prop_id'])) {
            $where['prop_id'] = (int) $get['prop_id'];
        }
        if (!empty($get['prop_tag'])) {
            $where['change_tag'] = $get['prop_tag'];
        }

        if (!empty($get['login_name'])) {
            $ids = \common\models\user\User::searchByName($get['login_name']);
            $where['user_id'] = $ids;
        }

        if(!empty($startTime) && empty($endTime)) {
            $andWhere = ['>','change_time',$startTime];
        } elseif(empty($startTime) && !empty($endTime)) {
            $andWhere = ['<','change_time',$endTime];
        } elseif (!empty($startTime) && !empty($endTime)) {
            $andWhere = ['between','change_time',$startTime, $endTime];
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query) {
        if (empty($query)) {
            return null;
        }

        $list = $query->with(['user'])->asArray()->all();

        foreach($list as $key => $value) {
            $uerInfo = ArrayHelper::getValue($value,'user',[]);
            $list[$key]['login_name'] = $uerInfo ? $uerInfo['login_name'] : '';
            $list[$key]['nick_name'] = $uerInfo ? $uerInfo['nick_name'] : '';
            $list[$key]['user_face'] = $this->getImages($uerInfo['user_face']);

//            $list[$key]['change_type'] = Status::MONEY_LOG_TYPE_MAP[$value['change_type']] ?? '';
            $list[$key]['change_type'] = $value['change_tag'] ?: '';
            $list[$key]['prop_id'] = Status::PROP_TYPE_MAP[$value['prop_id']] ?? '';

            $list[$key]['num'] = floatval($value['num']);
            $list[$key]['before_change'] = floatval($value['before_change']);
            $list[$key]['after_change'] = floatval($value['after_change']);
        }
        return $list;
    }

    public function getFullList($status = 0) {
        try {
            foreach (Status::PROP_TYPE_MAP as $k => $v) {
                $data = [
                    'id' => (int) $k,
                    'is_prod' => (int) $k,
                    'name' => $v,
                ];

                $result[] = $data;
            }
            return Functions::formatRestAPI(0, '', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getTags() {
        $get = Yii::$app->request->get();
        $map = Status::USER_CHANGE_TAG_MAP[$get['id']];

        $tmp = [];
        foreach ($map as $v) {
            $tmp[] = [
                "name" => $v
            ];
        }

        return $tmp;
    }


    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @param array $search
     * @return array
     */
    public function getUserListData($page = 1, $size = 20) {
        try {

            //搜索条件
            $searchWhere  = $this->getUserSearch();//自定义搜索条件
            $query = new \common\models\UserMoneyLog();
            //得到文章的总数
            $count = $query::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'change_time DESC, id DESC';

            $query = $query::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);

            $data['data'] = $this->handeUserlList($query);

            $summary = static::getOneByAndWhere($searchWhere['where'], $searchWhere['andWhere'], [
                "SUM(change_money) as change_money",
            ]);

            $totalMoney = User::getSumByWhere([], "balance");
//
//            $data['summary'] = [
//                "diff_income" => ["key" => "diff_income", "value" => $summary['diff_income']],
//                "self_diff_income" => ["key" => "self_diff_income", "value" => $summary['self_diff_income']],
//                "self_income" => ["key" => "self_income", "value" => $summary['self_income']],
//                "self_volume" => ["key" => "self_volume", "value" => $summary['self_volume']],
//                "team_volume" => ["key" => "team_volume", "value" => $summary['team_volume']],
//            ];

            $data['summary'] = [
                ["key" => "id", "value" => ''],
                ["key" => "user", "value" => ''],
                ["key" => "change_type", "value" => ''],
                ["key" => "change_money", "value" => (float) $summary['change_money']],
                ["key" => "before_change", "value" => ''],
                ["key" => "after_change", "value" => "当前总积分：" . $totalMoney],
                ["key" => "change_time", "value" => ''],
                ["key" => "mark", "value" => ''],
            ];

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @param $search
     * @return string
     */

    public function getUserSearch () {
        $where = [];
        $andWhere = [];
        $type = Yii::$app->request->get('type','');
        $loginName = Yii::$app->request->get('login_name','');
        $startTime = Yii::$app->request->get('start','');
        $endTime = Yii::$app->request->get('end','');
        $user_id = Yii::$app->request->get('user_id','');
        if (empty($user_id)) {
            throw new Exception('缺少用户信息');
        }
        $where['user_id'] = (int) $user_id;

        if ($type) {
            $where['change_type'] = $type;
        }

        if($loginName) {
            $userAndWhere[] = ['like','login_name',$loginName];
            $userId = User::getFormArrayAndWhere('',$userAndWhere,'id','id');
            $where['user_id'] = $userId;
        }

        if(!empty($startTime) && empty($endTime)) {
            $andWhere = ['>','change_time',$startTime];
        } elseif(empty($startTime) && !empty($endTime)) {
            $andWhere = ['<','change_time',$endTime];
        } elseif (!empty($startTime) && !empty($endTime)) {
            $andWhere = ['between','change_time',$startTime, $endTime];
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere,
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handeUserlList($query) {
        if (empty($query)) {
            return null;
        }

        $list = $query->with(['user'])->asArray()->all();

        foreach($list as $key => $value) {
            $uerInfo = ArrayHelper::getValue($value,'user',[]);
            $list[$key]['login_name'] = $uerInfo ? $uerInfo['login_name'] : '';
            $list[$key]['nick_name'] = $uerInfo ? $uerInfo['nick_name'] : '';
            $list[$key]['user_face'] = $this->getImages($uerInfo['user_face']);

            $list[$key]['change_type'] = Status::USER_MONEY_CHANGE_TYPE_MAP[$value['change_type']] ?? '';

            $list[$key]['change_money'] = floatval($value['change_money']);
            $list[$key]['before_change'] = floatval($value['before_change']);
            $list[$key]['after_change'] = floatval($value['after_change']);
        }
        return $list;
    }


}
